<template>
  <div class="container">
	<div class="btnBox">
		<el-button @click="upset" round type="primary" class="btn">{{ state.gameStart ? '重新开始' : '开始游戏'}}</el-button>
	</div>
	<div class="gameData" v-if="state.gameView">
		<div class="data">
			步数：{{ state.stepsNumber }}
		</div>
		<div class="data">
			用时： {{ state.one }} : {{ state.two }} : {{ state.three }}
		</div>
		<div class="gameBorder">
			<div class="gameBox">
				<div
				v-for="(item, index) in state.numList"
				class="sBox"
				:key="index"
				@click="boxMove(item.index, index)"
				:id="`sBox${index}`"
				>
				{{ item.num }}
				</div>
			</div>
		</div>
	</div>
	<div class="hitstory">
		历史最佳
		<div v-if="stores.bestAchievement.stepsNumber == 0">
			暂无
		</div>
		<div v-else>
			<div>
				步数： {{ stores.bestAchievement.stepsNumber }}
			</div>
			<div>
				用时： {{ stores.bestAchievement.time }}
			</div>
		</div>
	</div>
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, computed } from "vue";
import { reactive } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import lodash from 'lodash';
import { testStores } from '@/stores/modules/test';
const stores = testStores();
const isTrue = computed(() => {
	var compare = function (prop) {
		return function (obj1, obj2) {
			var val1 = obj1[prop];
			var val2 = obj2[prop];
			if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
				val1 = Number(val1);
				val2 = Number(val2);
			}
			if (val1 < val2) {
				return -1;
			} else if (val1 > val2) {
				return 1;
			} else {
				return 0;
			}
		}
	}
	let numList = lodash.cloneDeep(state.numList).sort(compare('num'))
	return JSON.stringify(numList) === JSON.stringify(state.numListOld)
})
const state = reactive({
	numListOld: [
		{
			num: 1,
			index: 0,
		},
		{
			num: 2,
			index: 1,
		}, {
			num: 3,
			index: 2,
		},
		{
			num: 4,
			index: 3,
		}, 
		{
			num: 5,
			index: 4,
		},
		{
			num: 6,
			index: 5,
		},
		{
			num: 7,
			index: 6,
		},
		{
			num: 8,
			index: 7,
		},
	],
	numList: [
		{
			num: 1,
			index: 0,
		},
		{
			num: 2,
			index: 1,
		}, {
			num: 3,
			index: 2,
		},
		{
			num: 4,
			index: 3,
		},
		{
			num: 5,
			index: 4,
		},
		{
			num: 6,
			index: 5,
		},
		{
			num: 7,
			index: 6,
		},
		{
			num: 8,
			index: 7,
		},
	],
  	blankIndex: 8, //空白下标
	transverse: false, // 纵向横向
	stepsNumber: 0, // 步数
	flag: null,
	one: '00', // 时
	two: '00', // 分
	three: '00', // 秒
	abc: 0, // 秒的计数
	cde: 0, // 分的计数
	efg: 0, // 时的计数
	gameStart: false, // 游戏是否开始
	gameView: true,
});

const upset = (async ()  => {
	state.stepsNumber = 0;
	await startHandler();
	let arr = state.numList.map((item) => item.index)
	let  arr1, arr2;
	let length = arr.length, randomIndex,temp;
	while (length) {
		randomIndex = Math.floor(Math.random() * (length--));
		temp = arr[randomIndex];
		arr[randomIndex] = arr[length];
		arr[length] = temp
	}
	arr1 = arr.splice(0,4)
	arr2 = arr
	for(let i = 0; i < 4;i++) {
		let num = state.numList[arr1[i]].num;
		state.numList[arr1[i]].num = state.numList[arr2[i]].num;
		state.numList[arr2[i]].num = num;
	}
	
})

const boxMove = (index: number, idx: number) => {
	if(!state.gameStart) {
		 ElMessage({
			type: 'warning',
			message: '请先开始游戏',
		})
		return;
	};
	let difference = Math.abs((index - state.blankIndex));
	let type = "";
	if (difference != 1 && difference != 3) {
		return;
	}
	if (index - state.blankIndex == 1) {
		if (index == 3 || index == 6) return
		type = 'left'
	} else if (index - state.blankIndex == -1) {
		if(index == 2 || index == 5) return
		type = 'right'
	} else if (index - state.blankIndex == 3) {
		type = 'top'
	} else {
		type = 'bottom'
	}
	state.stepsNumber += 1;
	state.numList[idx].index = state.blankIndex;
	state.blankIndex = index;
	var boxDom = document.querySelector(`#sBox${idx}`);
  let x = 0;
  let y = 0;
  if (boxDom?.style.transform) {
    x = Number(getTranslate(boxDom?.style.transform)[0]);
    y = Number(getTranslate(boxDom?.style.transform)[1]);
    if (type == "right") {
      x += 150;
    } else if (type == "left") {
      x -= 150;
    } else if (type == "top") {
      y -= 150;
    } else if (type == "bottom") {
      y += 150;
    }
    boxDom.style.transform = `translate(${x}px, ${y}px)`;
  } else {
    if (type == "right") {
      x += 150;
    } else if (type == "left") {
      x -= 150;
    } else if (type == "top") {
      y -= 150;
    } else if (type == "bottom") {
      y += 150;
    }
    boxDom.style.transform = `translate(${x}px, ${y}px)`;
  }
	if(isTrue.value) {
		stores.getBestAchievement(state.stepsNumber,`${state.one}:${state.two}:${state.three}`)
		ElMessageBox.confirm(
			`通关成功, 您的用时为 ${state.one}:${state.two}:${state.three} ,步数为 ${state.stepsNumber} 步`,
			'牛啊牛啊',
			{
				confirmButtonText: '再次挑战',
				cancelButtonText: '取消',
				type: 'success',
			}
		)
			.then(() => {
				upset();
			})
			.catch(() => {
			})
		endHandler();
	}

};
const getTranslate = (str: any) => {
  return str.slice(10, -3).trim().split("px, ");
};
const startHandler = () => {
	state.blankIndex = 8; //空白下标
	state.numList = lodash.cloneDeep(state.numListOld)
	
	state.gameStart = true;
	state.gameView = false;
	setTimeout(() => {
		state.gameView = true;
	},1)
	state.three = '00';
	state.abc = 0;
	state.two = '00';
	state.cde = 0;
	state.one = '00';
	state.efg = 0;
	state.flag = clearInterval(state.flag)
	state.flag = setInterval(() => {
		if (state.three === 60 || state.three === '60') {
			state.three = '00';
			state.abc = 0;
			if (state.two === 60 || state.two === '60') {
				state.two = '00';
				state.cde = 0;
				if (state.efg + 1 <= 9) {
					state.efg++;
					state.one = '0' + state.efg;
				} else {
					state.efg++;
					state.one = state.efg;
				}
			} else {
				if (state.cde + 1 <= 9) {
					state.cde++;
					state.two = '0' + state.cde;
				} else {
					state.cde++;
					state.two = state.cde;
				}
			}
		} else {
			if (state.abc + 1 <= 9) {
				state.abc++;
				state.three = '0' + state.abc;
			} else {
				state.abc++;
				state.three = state.abc;
			}
		}

	}, 1000)
}
const endHandler = () => {
	state.flag = clearInterval(state.flag)
	state.gameStart = false;
}
</script>
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
}
.hitstory {
	padding: 10px;
	position: absolute;
	top: calc(50vh - 150px);
	left: 20px;
	width: 200px;
	height: 200px;
	background-image: url(/src/assets/block.jpg);
	color: #422121;
	font-size: 16px;
	font-weight: bold;
	text-align: center;
}
.gameData {
	margin: 0px auto;
	width: 480px;
	height: 600px;
	.data {
		display: inline-block;
		width: 160px;
		height: 40px;
		margin: 20px;
		background-image: url('../../assets/block.jpg');
		border-radius: 20px;
		line-height: 40px;
		font-size: 16px;
		font-weight: bold;
		color: #422121;
		text-indent: 1em;
	}
}
.gameBorder {
	width: 480px;
	height: 480px;
	padding: 15px;
	border-radius: 5px;
	background-image: url('../../assets/border.jpg');
}
.gameBox {
  width: 452px;
  height: 452px;
background-image: url('../../assets/background.webp');
  display: flex;
  flex-wrap: wrap;
		border: 1px solid black;
		border-radius: 10px;
  .sBox {
    width: 150px;
    height: 150px;
		border: 1px solid black;
		border-radius: 10px;
		background-image: url('../../assets/block.jpg');
    // background: skyblue;
    line-height: 150px;
		color: #422121;
		font-weight: bold;
    font-size: 60px;
    text-align: center;
    transition-duration: 0.1s;
    transition-timing-function: linear;
	box-sizing: border-box;
	cursor: pointer;
	-moz-user-select: none;
	/*火狐*/
	-webkit-user-select: none;
	/*webkit浏览器*/
	-ms-user-select: none;
	/*IE10*/
	-khtml-user-select: none;
	/*早期浏览器*/
	user-select: none;
  }
}
.btnBox {
	margin: 100px auto;
	width: 100px;
	.btn {
		margin: 0px auto;
		width: 100px;
	}
}
</style>
